package com.xiangyi.teachingsystem.controller;

import com.xiangyi.teachingsystem.entity.dto.MessageDto;
import com.xiangyi.teachingsystem.entity.po.Message;
import com.xiangyi.teachingsystem.entity.vo.Result;
import com.xiangyi.teachingsystem.service.MessageService;
import com.xiangyi.teachingsystem.service.UserGroupService;
import com.xiangyi.teachingsystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class MessageController {
    @Autowired
    MessageService messageService;
    @Autowired
    UserGroupService userGroupService;
    @Autowired
    UserService userService;

    @PostMapping("/addMessage")
    public Result addMessage(@Validated @RequestBody Message message){
        if (userGroupService.getById(message.getGroupId())==null)
            return Result.failure("小组不存在，请检查groupId");
        if (userService.getById(message.getUserId())==null)
            return Result.failure("用户不存在，请检查userId");

        try {
            messageService.save(message);
            return Result.success("信息发送成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.failure("服务器错误").setData(e.getMessage());
        }
    }

    @GetMapping("/msgList")
    public Result msgList(@RequestParam Integer groupId){
        List<MessageDto> messageDtoList= messageService.infoList(groupId);
        return Result.success("短消息查询成功").setData(messageDtoList);
    }
}
